import toolCache from "../tool-cache";
import toolHttp from "./tool-axios";

let excludeField = [
  "id",
  "created_by",
  // "created_date",
  "updated_by",
  "updated_date",
  "flag",
  "version",
];

const toolAction = {
  init(name, _dsId) {
    let apiAction = {
      list(data) {
        return toolHttp.post(`/action/action-table-list/${name}`, {
          ...data,
          _dsId,
        });
      },
      page(data) {
        return toolHttp.post(`/action/action-table-page/${name}`, {
          ...data,
          _dsId,
        });
      },
      async remove(data) {
        return await toolHttp.post(`/action/action-table-remove/${name}`, {
          ...data,
          _dsId,
        });
      },
      view(data) {
        return toolHttp.post(`/action/action-table-view/${name}`, {
          ...data,
          _dsId,
        });
      },
      async meta() {
        let metas = await toolHttp.post(`/action/action-table-info/${name}`, {
          _dsId,
        });
        metas.forEach((item) => {
          item.memo = item.memo || item.name;
          if (excludeField.includes(item.name)) {
            item.hidden = true;
          }
        });
        return metas;
      },
      sync(data) {
        return toolHttp.post(`/action/action-table-sync/${name}`, {
          ...data,
          _dsId,
        });
      },
      async dict(key = "name", val = "id", data) {
        try {
          let dictVal = await toolCache.cache(
            `dict-${name}-${key}-${val}`,
            async () => {
              let res = await apiAction.list(data);
              return res.map((item) => ({
                name: item[key] || item[val] || "未知名称",
                val: item[val],
              }));
            },
            3 * 1000
          );
          return dictVal;
        } catch (e) {
          console.error(`字典数据[${name}]异常，请联系管理员处理...`);
          return [];
        }
      },
      async tree(data) {
        let res = await apiAction.list(data);
        return listToTree(res);
      },
    };
    return apiAction;
  },
  run(action, code, data) {
    return toolHttp.post(`/action/${action}/${code}`, data);
  },
  list(data) {
    return toolHttp.get(`/action`, data);
  },
  enumDict(code, data) {
    return this.run("action-enum-dict", code, data);
  },
};
/**
 * 顶级pKey的值为 0，或者空
 */
function listToTree(list = [], pKey = "pid", key = "id") {
  function treeChildren(val) {
    let childrenList = list.filter((item) => item[pKey] == val);
    if (childrenList.length < 1) {
      return [];
    }
    childrenList.forEach((childrenListItem) => {
      childrenListItem.val = childrenListItem.id;
      let childrenListTemp = treeChildren(childrenListItem[key]);
      if (childrenListTemp.length > 0) {
        childrenListItem.children = childrenListTemp;
      }
    });
    return childrenList;
  }
  return [...treeChildren(0)];
}

export default toolAction;
